package com.example.distributelock.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author caryguan
 * @version V1.0
 * @Package com.example.distributelock.lock
 * @date 2020/10/8 22:10
 */
@Slf4j
//实现自动关闭接口1.7引入的JDK接口
public class RedisLock implements AutoCloseable {

    @Autowired
    private RedisTemplate redisTemplate;

    private String key;

    private String value;

    //单位:秒
    private int expireTime;

    public RedisLock(RedisTemplate redisTemplate, String key, int expireTime) {
        this.redisTemplate = redisTemplate;
        this.key = key;
        this.value = UUID.randomUUID().toString();
        this.expireTime = expireTime;
    }

    //获取分布式锁
    public boolean getLock() {
        //TIPS 这里我们要执行实现redis实现分布式锁set nx的方法,如果成功为true,所以返回一个布尔值
        RedisCallback<Boolean> redisCallback = connection -> {
            //ifAbsent方法代表如果锁存在设置不成功,不存在设置成功
            RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.ifAbsent();
            Expiration expiration = Expiration.seconds(expireTime);
            //直接使用key.getBytes是不行的 String的getBytes()方法是得到一个操作系统默认的编码格式的字节数组。这就表明在不同的操作系统下,返回的编码是不一样的！
            // byte[] redisKey = key.getBytes();
            //设置过期时间序列化key
            byte[] redisKey = redisTemplate.getKeySerializer().serialize(key);
            //设置过期时间序列化value
            byte[] redisValue = redisTemplate.getValueSerializer().serialize(value);

            //键 值 过期时间 设置策略 执行set nx操作
            Boolean result = connection.set(redisKey, redisValue, expiration, setOption);
            return result;
        };

        Boolean lock = (Boolean) redisTemplate.execute(redisCallback);
        return lock;
    }

    public boolean unLock() {
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        RedisScript<Boolean> redisScript = RedisScript.of(script, Boolean.class);

        List<String> keys = Arrays.asList(key);
        Boolean result = (Boolean) redisTemplate.execute(redisScript, keys, value);
        log.info("释放锁的结果:" + result);
        return result;
    }

    @Override
    public void close() throws Exception {
        unLock();
    }
}